/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.evangelion.core.utils;

import com.evangelion.core.bean.Seccione;
import com.evangelion.core.dao.GenericDao;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.inject.Named;
import java.io.Serializable;
import java.util.List;

@Named("seccionConverter")
public class SeccionConverter implements Converter, Serializable {

    public static List<Seccione> linkTypesDB;
    @Autowired
    private GenericDao gd;

    @PostConstruct
    public void initLinkTypesDBList() {
        linkTypesDB = gd.ListAll(Seccione.class);
    }

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        if (s.trim().equals("")) {
            return null;
        } else {
            try {
                int number = Integer.parseInt(s);

                for (Seccione lt : linkTypesDB) {
                    if (lt.getId() == number) {
                        return lt;
                    }
                }
            } catch (NumberFormatException exception) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid converter"));
            }
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
        if (o == null || o.equals("")) {
            return "";
        } else {
            return String.valueOf(((Seccione) o).getId());
        }
    }

    public GenericDao getGd() {
        return gd;
    }

    public void setGd(GenericDao gd) {
        this.gd = gd;
    }
}
